﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

using RRRSRoguelike.Enums;
using RRRSRoguelike.Helpers.Visualizer;
using RRRSRoguelike.Managers;
using RRRSRoguelikeData;
using RRRSRoguelike.Helpers.Webservice;

namespace RRRSRoguelike.Screens
{
	/// <summary>
	/// Manages the UI to prompt user for high score service.
	/// </summary>
	class HighScoreScreen : Screen
	{
		HighScoreAPI hs = new HighScoreAPI();

		public HighScoreScreen()
		{
			PanelList.Add(new Panel(new Point(4, 3),
			                        Visualizer.GetScreenWidth() - 9, Visualizer.GetScreenHeight() - 6));
		}

		public override void Show()
		{
			Clear();

			foreach (Panel p in PanelList)
			{
				p.Clear();
				p.Draw();
			}

			//Temp place holder for score, need to set this to actual score value
			string name = ApplicationManager.Instance.Profile.Name;
			
			PanelList[0].Clear();
			
			Session session = ApplicationManager.Instance.Profile.Session;

			string[] names = Enum.GetNames(typeof(HighScoreEntries));
			
			int[] colWidths = new int[names.Length];
			for (int i = 0; i < names.Length;i++)
			{
				//colWidths[i] = names[i].Length + 2;
				colWidths[i] = 17;
			}
			colWidths[(int)HighScoreEntries.Name] = 17;
			//HACK: We should limit ruleset names to 15chars
			colWidths[(int)HighScoreEntries.Ruleset] = 17;
			
			//Add new score
			if (session.tempScore.Data.Count > 0)
				ApplicationManager.Instance.Profile.HighScores.Entries.Add((HighScoreEntry)session.tempScore.Clone());
			
			//Sort scores
			if(ApplicationManager.Instance.Profile.HighScores.Entries.Count > 2)
				ApplicationManager.Instance.Profile.HighScores.Entries.Sort(
					
					delegate(HighScoreEntry s1, HighScoreEntry s2)
					{
						int compareEntry = int.Parse(s2.Data["Score"]).CompareTo(int.Parse(s1.Data["Score"]));
						
						return compareEntry;
					}
				);
			
			//headings
			PanelList[0].Write(Visualizer.PrepareRow(
				names,
				colWidths),0);
			
			//scores
			int maxEntries = Math.Min(ApplicationManager.Instance.Profile.HighScores.Entries.Count,10);
			for(int i = 0; i< maxEntries;i++)
			{
				List<string> tempList = ApplicationManager.Instance.Profile.HighScores.Entries[i].Data.Values.ToList<string>();

				//Highlight recent score
				ConsoleColor cc = ConsoleColor.White;
				if (session.tempScore.Data.Count > 0){
				if (tempList[0] == ApplicationManager.Instance.Profile.Session.tempScore.Data["ID"])
					cc = ConsoleColor.Cyan;
				}
				//remove ID
				tempList.RemoveAt(0);
				
				
				string[] values = (string[])tempList.ToArray();
				PanelList[0].Write(Visualizer.PrepareRow(values,
				                                         colWidths),1+i, cc);
			}
			
			if (session.tempScore.Data.Count > 0)
			ApplicationManager.Instance.Profile.Save();
			
			WaitKey();
			
			if (session.tempScore.Data.Count > 0)
			UploadScore(name);
		}


		//prompt user

		//temp placeholder for unique ID to so only game can update webservice


		//read keyboard
		//answer = Console.ReadKey(true).Key;

		//is y pressed?



		//HACK: culture string
		void UploadScore(string name)
		{
			PanelList[0].Clear();
			PanelList[0].Write(Properties.Strings.HighScore + Properties.Strings.YNQuestion);
			string guid = "guid94723";
			ConsoleKey answer;
			while (true) {
				answer = Console.ReadKey(true).Key;
				if (answer == ConsoleKey.Y) {
					var currentScore = ApplicationManager.Instance.Profile.Session.tempScore.Data["Score"];
					string currentRuleset = ApplicationManager.Instance.Profile.Session.tempScore.Data["Ruleset"];
					string currentVersion = ApplicationManager.Instance.Profile.Session.tempScore.Data["Version"];
					string currentSeed = ApplicationManager.Instance.Profile.Session.tempScore.Data["Seed"];
					try {
						hs.SubmitScore(guid, name, Convert.ToInt32(currentScore), currentRuleset, currentVersion, Convert.ToInt32(currentSeed));
						break;
					} catch {
						PanelList[0].Clear();
						PanelList[0].Write("Service unavailable.");
						WaitKey();
					}
				} else if (answer == ConsoleKey.N) {
					break;
				} else {
					answer = Console.ReadKey().Key;
				}
			}
		}
		

		void Draw()
		{
			Clear();
			PanelList[0].Draw();
		}
	}
}
